#include "FileServer.h"
#include <QDebug>



FileServer::FileServer(QObject *parent)
    : QObject(parent),
    tcpServer(new QTcpServer(this))
{
    connect(tcpServer, &QTcpServer::newConnection, this, &FileServer::onNewConnection);
}

FileServer::~FileServer()
{
    qDebug() << "~FileServer";
    delete tcpServer;
}

bool FileServer::startServer(quint16 port)
{
    if (!tcpServer->listen(QHostAddress::Any, port)) {
        qDebug() << "Server could not start!";
        return false;
    } else {
        qDebug() << "Server started on port:" << port;
        return true;
    }
}

void FileServer::onNewConnection()
{
    QTcpSocket *clientSocket = tcpServer->nextPendingConnection();
    connect(clientSocket, &QTcpSocket::readyRead, this, &FileServer::onReadyRead);
    connect(clientSocket, &QTcpSocket::disconnected, this, &FileServer::onDisconnected);

    qDebug() << "New client connected:" << clientSocket->peerAddress().toString();
}

void FileServer::onReadyRead()
{
    QTcpSocket *clientSocket = qobject_cast<QTcpSocket*>(sender());
    if (!clientSocket) return;

    QDataStream inStream(clientSocket);
    Header header;
    quint64 fileSize;
    FileInformation fileInformation;

    inStream >> header;
    inStream >> fileSize;
    inStream >> fileInformation;

    qDebug() << "收到文件信息"
             << "文件大小" << fileSize
             << "文件名称" << fileInformation.fileName
             << "发送时间" << fileInformation.send_time;

    QFile *file = new QFile(fileInformation.fileName, this);
    if(!file->open(QIODevice::WriteOnly))
    {
        qDebug() << "文件创建或打开失败" << file->errorString();
        delete file;
        return;
    }

    const qint64 chunkSize = 64 * 1024; // Same chunk size as sender
    QByteArray buffer;
    qint64 totalBytesReceived = 0;

    while (totalBytesReceived < fileSize) {
        if (clientSocket->bytesAvailable() < chunkSize && !clientSocket->waitForReadyRead(10000)) {
            qDebug() << "等待数据超时";
            break;
        }

        buffer = clientSocket->read(chunkSize);
        if (buffer.isEmpty()) {
            qDebug() << "接收到空数据，可能因为连接出错";
            break;
        }

        file->write(buffer);
        // 发送更新信号
        emit onGettingFile(totalBytesReceived,fileSize);
        totalBytesReceived += buffer.size();
        qDebug() << "接收到的数据大小" << buffer.size() << "总数据大小" << totalBytesReceived;
    }

    file->flush(); // Ensure all data is written
    qDebug() << "最终数据大小" << file->size();

    // 回复发送端
    QDataStream reply(clientSocket);
    if(file->size() != fileSize)
    {
        reply << RECEIVE_FILE_ERROR;
    }
    file->close();
    reply << RECEIVE_FILE_OK;
    clientSocket->flush();
    delete file;

}


void FileServer::onDisconnected()
{
    QTcpSocket *clientSocket = qobject_cast<QTcpSocket*>(sender());
    if (!clientSocket) return;

    clientSocket->deleteLater();
    qDebug() << "Client disconnected.";
}
